<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户账号" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户账号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input v-model="queryParams.licensePlate" placeholder="请输入车牌号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="ebikeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车牌号" align="center" prop="licensePlate" />
      <el-table-column label="姓名" align="center" prop="nickName" />
      <el-table-column label="用户账号" align="center" prop="userName" />
      <el-table-column label="联系电话" align="center" prop="phonenumber" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="记分" align="center" prop="points" />
      <el-table-column label="违规状态" align="center" prop="violationStatus">
        <template #default="scope">
          <dict-tag :options="violation_status" :value="scope.row.violationStatus" :class="{
            'no-violation': scope.row.violationStatus === 0,
            'has-violation': scope.row.violationStatus === 1,
            'full-violation': scope.row.violationStatus === 2
          }" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="getDetailsInfo(scope.row)"
            v-hasPermi="['violation:handling:list']">详情</el-button>
          <el-button link type="primary" @click="handleClearPoints(scope.row)"
            v-hasPermi="['violation:collectionRecord:remove']">销分</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改车辆信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ebikeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="form.licensePlate" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="车辆图片" prop="vehicleImage">
          <image-upload v-model="form.vehicleImage" />
        </el-form-item>
        <el-form-item label="车架号" prop="frameNumber">
          <el-input v-model="form.frameNumber" placeholder="请输入车架号" />
        </el-form-item>
        <el-form-item label="电瓶生产日期" prop="batteryProductionDate">
          <el-date-picker clearable v-model="form.batteryProductionDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择电瓶生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="电瓶有效期" prop="batteryExpiryDate">
          <el-date-picker clearable v-model="form.batteryExpiryDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择电瓶有效期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看车辆详情对话框 -->
    <el-dialog title="车辆详情" v-model="DetailsInfoOpen" width="500px" append-to-body>
      <el-row>
        <el-col :span="12">
          <el-form-item label="人员类别">
            <dict-tag :options="user_type" :value="form.userType" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户状态">
            <dict-tag :options="sys_user_status" :value="form.status" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">二维码ID：{{ form.qrId }}</el-col>
        <el-col :span="12">车架号：{{ form.frameNumber }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">电瓶生产日期：{{ form.batteryProductionDate }}</el-col>
        <el-col :span="12">电瓶有效期：{{ form.batteryExpiryDate }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="车辆图片">
            <img :src="form.vehicleImage" alt="车辆图片" style="width: 100%; max-height: 300px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 违规记录展示 -->
      <el-row>
        <el-col :span="24">
          <el-table :data="collectionRecords" border style="width: 100%">
            <el-table-column prop="collectionId" label="采集ID" width="80"></el-table-column>
            <el-table-column prop="violationPlace" label="违规地点" width="100">
              <template #default="scope">
                <dict-tag :options="violation_place" :value="scope.row.violationPlace" />
              </template>
            </el-table-column>
            <el-table-column prop="violationType" label="违规类型" width="100"></el-table-column>
            <el-table-column prop="createTime" label="违规时间" width="100">
              <template #default="scope">
                {{ formatTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="violationPoints" label="违规扣分" width="80"></el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup name="Ebike">
import dayjs from 'dayjs';
import { listCollectionRecord, delCollectionRecord } from "@/api/violation/collectionRecord";
import { listEbike, getEbike, delEbike, addEbike, updateEbike, getDetails } from "@/api/vehicle/ebike";

const { proxy } = getCurrentInstance();
const { user_type, type } = proxy.useDict('user_type', 'type');
const { sys_user_status, status } = proxy.useDict('sys_user_status', 'status');
const { violation_place, violationPlace } = proxy.useDict('violation_place', 'violationPlace');
const { violation_status, violationStatus } = proxy.useDict('violation_status', 'violationStatus');

const ebikeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const collectionRecords = ref([]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    licensePlate: null,
  },
  rules: {
    userName: [
      { required: true, message: "用户账号不能为空", trigger: "blur" }
    ],
    licensePlate: [
      { required: true, message: "车牌号不能为空", trigger: "blur" }
    ],
    vehicleImage: [
      { required: true, message: "车辆图片不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


const DetailsInfoOpen = ref(false);

// 在你的方法中使用 dayjs 进行格式化
function formatTime(time) {
  return dayjs(time).format('YYYY-MM-DD');
}

/** 销分按钮操作 */
function handleClearPoints(row) {
  const licensePlate = row.licensePlate;
  proxy.$modal.confirm(`是否确认销分车牌号为"${licensePlate}"的所有违规采集记录？`).then(function () {
    // 获取所有违规采集记录
    listCollectionRecord({ licensePlate: licensePlate }).then(response => {
      const collectionIds = response.rows.map(item => item.collectionId);
      // 删除所有违规采集记录
      delCollectionRecord(collectionIds.join(',')).then(() => {
        getList();
        proxy.$modal.msgSuccess("销分成功");
        // 更新 ebike 记分
        updateEbikePoints(licensePlate, null, true);
      }).catch(() => {
        proxy.$modal.msgError("销分失败");
      });
    }).catch(() => {
      proxy.$modal.msgError("获取违规采集记录失败");
    });
  }).catch(() => { });
}

// 更新 ebike 记分，增加 isClear 参数
function updateEbikePoints(licensePlate, violationType, isClear = false) {
  // 先查找对应的 ebike 记录
  listEbike({ licensePlate: licensePlate }).then(response => {
    if (response.rows.length > 0) {
      const ebike = response.rows[0];
      if (isClear) {
        // 如果是销分，则将记分清零
        ebike.points = 0;
      } else {
        // 获取违规类型的记分
        getViolationPoints(violationType).then(response => {
          const violationPoints = response.data;
          // 更新记分
          ebike.points += parseInt(violationPoints, 10);
        }).catch(() => {
          proxy.$modal.msgError("获取违规类型记分失败");
          return;
        });
      }
      // 调用更新 ebike 的 API
      updateEbike(ebike).then(() => {
        proxy.$modal.msgSuccess("车辆记分更新成功");
      }).catch(() => {
        proxy.$modal.msgError("车辆记分更新失败");
      });
    } else {
      proxy.$modal.msgError("未找到对应的车辆记录");
    }
  });
}

/** 查看车辆违规详情 */
function getDetailsInfo(row) {
  reset();
  const _ebikeId = row.ebikeId
  getDetails(_ebikeId).then(response => {
    form.value = response.data;
    collectionRecords.value = response.data.collectionRecords; // 获取违规记录
    DetailsInfoOpen.value = true;
  });
}

/** 查询车辆信息列表 */
function getList() {
  loading.value = true;
  listEbike(queryParams.value).then(response => {
    ebikeList.value = response.rows
      .map(row => ({
        ...row,
        violationStatus: calculateViolationStatus(row.points) // 计算违规状态
      }))
      .filter(row => row.violationStatus !== 0); // 过滤掉无违章的车辆
    total.value = response.total;
    loading.value = false;
  });
}

// 添加计算违规状态的方法
function calculateViolationStatus(points) {
  if (points >= 12) {
    return 2; // 满分
  } else if (points > 0) {
    return 1; // 有违章
  } else {
    return 0; // 无违章
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    ebikeId: null,
    userName: null,
    licensePlate: null,
    qrId: null,
    vehicleImage: null,
    points: null,
    frameNumber: null,
    batteryProductionDate: null,
    batteryExpiryDate: null,
    delFlag: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("ebikeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.ebikeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加车辆信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _ebikeId = row.ebikeId || ids.value
  getEbike(_ebikeId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改车辆信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ebikeRef"].validate(valid => {
    if (valid) {
      if (form.value.ebikeId != null) {
        updateEbike(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEbike(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ebikeIds = row.ebikeId || ids.value;
  proxy.$modal.confirm('是否确认删除车辆信息编号为"' + _ebikeIds + '"的数据项？').then(function () {
    return delEbike(_ebikeIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('vehicle/ebike/export', {
    ...queryParams.value
  }, `ebike_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style scoped>
.no-violation {
  background-color: #e6ffe6;
  /* 淡绿色背景 */
  color: #008000;
  /* 绿色文字 */

}

.has-violation {
  background-color: #e6f7ff;
  /* 淡蓝色背景 */
  color: #007bff;
  /* 蓝色文字 */
}

.full-violation {
  background-color: #ffe6e6;
  /* 淡红色背景 */
  color: #ff0000;
  /* 红色文字 */
}
</style>